### Illustrations of the equilibrium from the analytical model

date()
library("tidyverse")
sessionInfo()


## Implicitly fixing m_i = 1 for all three players
dat <- crossing(
    cost_1 = 1,
    cost_2 = 1:3,
    cost_3 = seq(1.0001, 4.5, length.out = 501)
)

## Calculate equilibrium for each set of parameters
dat <- dat %>%
    mutate(cost_total = cost_1 + cost_2 + cost_3,
           cost_max = pmax(cost_1, cost_2, cost_3),
           J = if_else(cost_total > 2 * cost_max, 3, 2),
           cost_total = if_else(J == 3, cost_total, cost_total - cost_max),
           q_1 = (J - 1) * cost_1 / cost_total,
           q_2 = (J - 1) * cost_2 / cost_total,
           q_3 = (J - 1) * cost_3 / cost_total,
           e_1 = if_else(J == 3 | cost_1 < cost_max, q_1 * (1 - q_1) / cost_1, 0),
           e_2 = if_else(J == 3 | cost_2 < cost_max, q_2 * (1 - q_2) / cost_2, 0),
           e_3 = if_else(J == 3 | cost_3 < cost_max, q_3 * (1 - q_3) / cost_3, 0),
           pr_win_a = (e_1 + e_2) / (e_1 + e_2 + e_3),
           cost_2 = factor(cost_2,
                           levels = 1:3,
                           labels = paste("c[2] ==", 1:3)))

plot_effort <- dat %>%
    select(cost_2, cost_3, e_1, e_2, e_3) %>%
    gather(key = player, value = effort, starts_with("e_")) %>%
    ggplot(aes(x = cost_3, y = effort)) +
    geom_line(aes(colour = player, linetype = player)) +
    facet_wrap(~ cost_2, labeller = label_parsed) +
    scale_x_continuous(expression(c[3])) +
    scale_y_continuous("Equilibrium effort") +
    scale_colour_brewer("Player", palette = "Set2",
                        labels = expression(e[1]^"*",e[2]^"*",e[3]^"*")) +
  scale_linetype("Player", labels = expression(e[1]^"*",e[2]^"*",e[3]^"*")) +
  theme(legend.position = "bottom")

plot_pr <- ggplot(dat, aes(x = cost_3, y = pr_win_a)) +
  geom_line() +
  facet_wrap(~ cost_2, labeller = label_parsed) +
  scale_x_continuous(expression(c[3])) +
  scale_y_continuous("Pr. Side A wins")

plot_width <- 6
plot_height <- 2.5

if (!dir.exists("figures"))
    dir.create("figures")
pdf(file = "figures/figure_1a.pdf",
    width = plot_width,
    height = 3)
print(plot_effort)
dev.off()

pdf(file = "figures/figure_1b.pdf",
    width = plot_width,
    height = 2.25)
print(plot_pr)
dev.off()


date()
